<?php


namespace App\Models\CacheModel;


use app\common\lib\SensorsData;
use App\Models\Api\BaseCache;
use App\Models\Api\Goods;
use think\Exception;

class CouponCode extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zl_coupon_code';

    public $errorMsg;

    private $couponTypeName = [
        1 => '折扣',
        2 => '立减',
        3 => '满减',
        4 => '随机',
        5 => '免费',
    ];

    /**
     * 优惠券搜索
     * @param string $code
     * @return array
     */
    public function search(string $code)
    {
        try
        {
            $data = $this->alias('cc')
                ->join('wechat_backup_07_18_14_43_00.zl_coupon_attr ca', 'ca.id=cc.c_id')
                ->where('cc.code', $code)
                ->field('cc.id,ca.name,ca.desc,cc.c_id,cc.expire_type,cc.expire_day,cc.expire_time,cc.ur_id ur_id1,ca.ur_id ur_id2,ca.type,ca.discount,ca.condition,cc.use_status,cc.is_give,ca.rand_min,ca.rand_max,ca.gids')
                ->findOrFail()->toArray();

            if ($data['use_status'] == 0 && $data['expire_type'] == 1 && $data['expire_time'] < time() && $data['expire_time'] > 0)
            {   // 如果 优惠券未使用 并且 固定时间到期 并且 时间已经过期
                $data['use_status'] = 2;
                // 修改为过期
                $this->save(['use_status' => 2], ['id' => $data['id']]);
            }

            $data['discount'] /= 100;
            $data['ur_id'] = $data['ur_id1'] !== 0 ? $data['ur_id1'] : $data['ur_id2'];
            unset($data['ur_id1'], $data['ur_id2']);
        }
        catch (Exception $e)
        {
            return [];
        }

        return $data;
    }

    /**
     * 优惠券领取
     * @param $uid
     * @param string $code
     * @return bool
     * @throws \Exception
     */
    public function codeGet($uid, string $code)
    {
        $data = $this->search($code);

        switch ($data['use_status'])
        {
            case 2:
                $this->errorMsg = '优惠券已失效';
                break;
            case 1:
                $this->errorMsg = '优惠券已领取';
                break;
            case 0:
                if ($data['expire_type'] == 1)
                {   // 固定到期时间
                    $endTime = $data['expire_time'];
                } else
                {   // 固定过期天数
                    $endTime = $data['expire_day'] !== 0 ? strtotime("+{$data['expire_day']} day") : 0;
                }
                $time = time();

                $price = $data['type'] == 4 ? mt_rand($data['rand_min'], $data['rand_max']) : 0;
                $cData[] = [
                    'uid' => $uid,
                    'c_id' => $data['c_id'],
                    'ur_id' => $data['ur_id'],
                    'start_time' => $time,
                    'end_time' => $endTime,
                    'give_time' => $time,
                    'status' => 0,
                    'price' => $price,
                    'is_give' => $data['is_give'],
                    'create_time' => $time,
                    'update_time' => 0
                ];

                $res = (new UserCoupon())->add($uid, $cData);
                if ($res)
                {
                    $this->save(['use_status' => 1, 'use_time' => $time, 'uid' => $uid], ['id' => $data['id']]);

                    $gidsArr = explode(',', $data['gids']);

                    $couponRangeArr = (new Goods())->where('id', 'in', $gidsArr)->column('name');
                    // 神策打点 75 获得优惠券 AcquireCoupon
                    SensorsData::track($uid, true, 'AcquireCoupon', [
                        'refer_name' => '',
                        'refer_link' => '',
                        'coupon_name' => $data['name'],
                        'coupon_expire' => date('Y-m-d H:i:s', $endTime),
                        'coupon_type' => $this->couponTypeName[$data['type']],
                        'coupon_range' => $couponRangeArr,
                        'acquire_channel' => '兑换码领取',
                        'is_give' => $data['is_give'] ? true : false,
                        'acquire_scene' => '兑换码领取',
                    ]);
                    return true;
                }
                $this->errorMsg = '服务异常；请稍后再试！';
                break;
            default:
                $this->errorMsg = '优惠券不存在';
        }

        return false;
    }
}
